package com.luych.toolbox.docker.service.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luych.toolbox.common.enums.TaskStatus;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketEventPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketLetterPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketNoticePublisher;
import com.luych.toolbox.common.feign.intf.base.service.TaskFeign;
import com.luych.toolbox.common.feign.intf.base.service.TaskLogFeign;
import com.luych.toolbox.common.feign.param.gateway.center.WebSocketEvent;
import com.luych.toolbox.common.feign.view.base.service.TaskView;
import com.luych.toolbox.docker.service.entity.DockerServer;
import com.luych.toolbox.docker.service.sdk.DockerClient;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DockerContainerRestartJob extends QuartzJobBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(DockerContainerRestartJob.class);

    private final BusProperties busProperties;
    private final ApplicationEventPublisher applicationEventPublisher;

    private final TaskFeign taskFeign;
    private final TaskLogFeign taskLogFeign;

    public DockerContainerRestartJob(BusProperties busProperties,
                                     ApplicationEventPublisher applicationEventPublisher,
                                     TaskFeign taskFeign,
                                     TaskLogFeign taskLogFeign) {
        this.busProperties = busProperties;
        this.applicationEventPublisher = applicationEventPublisher;
        this.taskFeign = taskFeign;
        this.taskLogFeign = taskLogFeign;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String id = context.getJobDetail().getJobDataMap().getString("id");

        WebSocketLetterPublisher letterPublisher = new WebSocketLetterPublisher(busProperties, applicationEventPublisher);
        WebSocketNoticePublisher noticePublisher = new WebSocketNoticePublisher(busProperties, applicationEventPublisher);
        WebSocketEventPublisher eventPublisher = new WebSocketEventPublisher(busProperties, applicationEventPublisher);

        TaskView task = taskFeign.get(id);
        Param stdin = Param.fromJson(task.getStdin());

        taskFeign.start(task.getId());

        String message = "容器重启通知";

        DockerClient dockerClient = new DockerClient(stdin.getServer().getUrl());
        try {
            dockerClient.containers().container(stdin.getId()).restart();
            taskFeign.complete(task.getId(), TaskStatus.SUCCESS, "成功");
            LOGGER.info("docker server {} restart container {} success", stdin.getServer().getName(), stdin.getName());

            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
            String content = "容器宿主机[" + stdin.getServer().getName() + "]重启容器[" + stdin.getName() + "]任务于" + datetime + "执行成功！";
            noticePublisher.success(task.getOwnerId(), content);
            letterPublisher.success(task.getOwnerId(), message, content);
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_CONTAINER_REFRESH, "RESTART"));
        } catch (Exception e) {
            LOGGER.error("docker server {} restart container {} error: {}", stdin.getServer().getName(), stdin.getName(), e.getMessage());
            StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));

            taskFeign.complete(task.getId(), TaskStatus.ERROR, e.getMessage());

            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
            String content = "容器宿主机[" + stdin.getServer().getName() + "]重启容器[" + stdin.getName() + "]任务于" + datetime + "执行异常，请及时处理。";
            noticePublisher.error(task.getOwnerId(), content);
            content += "\n\n\n错误信息：\n" + e.getMessage() + "\n\n\n异常堆栈：\n" + writer.toString();
            letterPublisher.error(task.getOwnerId(), message, content);
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_CONTAINER_REFRESH, "RESTART"));
        }
    }

    public static class Param {
        private DockerServer server;
        private String id;
        private String name;

        public DockerServer getServer() {
            return server;
        }

        public void setServer(DockerServer server) {
            this.server = server;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String toJson() {
            try {
                return new ObjectMapper().writeValueAsString(this);
            } catch (JsonProcessingException e) {
                throw new IllegalStateException(e);
            }
        }

        public static Param fromJson(String json) {
            try {
                return new ObjectMapper().readValue(json, Param.class);
            } catch (JsonProcessingException e) {
                throw new IllegalStateException(e);
            }
        }
    }
}
